package com.jin_mo.custom.utils;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @ProjectName: ModuleDev
 * @Package: com.jin_mo.custom.utils
 * @Description: 导入外部数据库
 * @Author: jin-mo
 * @CreateDate: 2021/10/21 18:07
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/10/21
 * @UpdateRemark: 更新说明
 */
public class GreenDaoCopyUtils {
    //数据库文件路径
    private static final String DB_PATH = "/data/data/包名/databases/";
    //数据库文件名
    private static final String DB_NAME = "guZheng.db";

    /**
     * 将assets文件夹下文件拷贝到/databases/下
     *
     * @param context
     */
    public static void copyDbFile(Context context) {
        InputStream in = null;
        FileOutputStream out = null;
        String path = "/data/data/" + context.getPackageName() + "/databases/";
        File file = new File(path + DB_NAME);

        //创建文件夹
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        if (file.exists()) {
            return;
        }

        try {
            // 从assets目录下复制
            in = context.getAssets().open(DB_NAME);
            out = new FileOutputStream(file);
            int length = -1;
            byte[] buf = new byte[1024];
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

//    public static void copyDbFile(Context context) throws IOException {
//        InputStream myInput = context.getAssets().open(DB_NAME);
//        File outFileName = context.getDatabasePath(DB_NAME);
//
//        outFileName.getParentFile().mkdirs();
//        OutputStream myOutput = new FileOutputStream(outFileName);
//        byte[] buffer = new byte[1024];
//        int length;
//        while ((length = myInput.read(buffer)) > 0) {
//            myOutput.write(buffer, 0, length);
//        }
//        myOutput.flush();
//        myOutput.close();
//        myInput.close();
//    }

}
